package com.flycent.hqhs.http;

import java.util.HashMap;
import java.util.Map;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;

import android.content.Context;

/** 处理web端返回的状态码
 *  Jason add 20141125
 *  Remove the Dialog from WebException ....
 *  
 *  
 *  */
public class WebException extends Exception {
	
	private static final long serialVersionUID = 2243871803993308349L;
	
	// custom error code
	public static final String TYPE_CHECK_NETWORK = "-1"; // 请检查网络
	public static final String TYPE_ERROR_NETWORK = "-2"; // 网络错误
	public static final String TYPE_SERVER_RETURN_NULL = "-3"; // 服务器无数据，处理content:null或者content:[]
	public static final String TYPE_SERVER_IS_NULL = "404"; // 404
	public static final String TYPE_SERVER_IS_ERROR = "500"; // 内部服务器错误 
	
	
	private Context context 	= null;
	private String statusCode 	= null; // web/本地 状态码
	
	
	
	// 错误码字典
	private static Map<String, String> errorMap = new HashMap<>();
	static {
		errorMap.put(TYPE_CHECK_NETWORK, "请检查网络");
		errorMap.put(TYPE_ERROR_NETWORK, "网络错误");
		errorMap.put(TYPE_SERVER_RETURN_NULL, "服务器无数据");
		errorMap.put(TYPE_SERVER_IS_NULL, "服务器错误");
		errorMap.put(TYPE_SERVER_IS_ERROR, "服务器内部错误");
		// error code from web
		// ...
	}
	
	//----------------------------------------------------
	
	/**
	 * @param context
	 * @param statusCode 状态码
	 */
	public WebException (Context context, String statusCode) {
		super();
		this.context = context;
		this.statusCode = statusCode;
	}
	
	/**
	 * @param context
	 * @param statusMessage 错误消息
	 */
	public WebException (Context context, String statusCode, String statusMessage) {
		super(statusMessage);
		this.context = context;
		this.statusCode = statusCode;
	}

	//----------------------------------------------------
	
	@Override
	public String getLocalizedMessage() {
		String statusMessage = getMessage();
		
		if (null != statusMessage) 		// web返回
			return statusMessage;
		else { 							// custom
			statusMessage = errorMap.get(statusCode);
			if (null != statusMessage)
				return statusMessage;
			else 
				return context.getString(R.string.error_msg, statusCode);
		}
	}
	
	@Override
	public void printStackTrace() {
		super.printStackTrace();
		if( "shop.common.unauthorized".equals(getStatusCode()) ){
			//when catch the login time out....
			App.showShortToast(R.string.please_login_too);
		}else {
			App.showShortToast(getLocalizedMessage());
		}
		
	}

	/** 返回状态码 */
	public String getStatusCode() {
		return statusCode;
	}


}
